package com.example.zyl.common.utils.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.example.zyl.common.CommonResult;
import lombok.Getter;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 邹阳林
 */
public class CommonLister<T> implements ReadListener<CommonExample> {


    Validator validator = null;

    {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }

    /**
     *校验成功的数据
     */
    @Getter
    private List<T> successList = new ArrayList<>();

    /**
     * 校验错误的数据
     */
    @Getter
    private List<T> errorList = new ArrayList<>();

    /**
     * 错误的返回报错信息
     */
    private List<String> errorMessageList = new ArrayList<>();

    @Override
    public void invoke(CommonExample example, AnalysisContext analysisContext) {
        if (example.check(analysisContext.readRowHolder().getRowIndex(), validator)) {
            successList.add((T) example);
        } else {
            errorList.add((T) example);
            errorMessageList.add(example.getReason());
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }


    public List<String> getErrorMessage() {
        return errorMessageList.stream().limit(10).collect(Collectors.toList());
    }

    public CommonResult<List<String>> getResponseResult() {
        String msg = "成功：" + this.getSuccessList().size() + "条，失败：" + this.getErrorList().size() + "条";
        return CommonResult.success(msg,this.getErrorMessage());
    }

    public List<String> getErrorMessageList() {
        return errorMessageList;
    }

    public void setSuccessList(List<T> successList) {
        this.successList = successList;
    }

    public void setErrorList(List<T> errorList) {
        this.errorList = errorList;
    }

    public void setErrorMessageList(List<String> errorMessageList) {
        this.errorMessageList = errorMessageList;
    }
}
